package at.newmedialab.sn.webservices.importer;

import at.newmedialab.sn.services.importer.SNImporterImpl;
import kiwi.core.model.user.KiWiUser;
import kiwi.core.qualifiers.user.CurrentUser;
import org.slf4j.Logger;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.UUID;

/**
 * User: Thomas Kurz
 * Date: 23.03.11
 * Time: 11:49
 */

@ApplicationScoped
@Path("/sn/importer")
public class SNImporterWebservice {

	@Inject
    private Logger log;

	@Inject
	private SNImporterImpl snImporter;

	@Inject @CurrentUser
    private KiWiUser currentUser;

	private static final ThreadGroup SN_IMPORTER_THREADS = new ThreadGroup("asynchronous sn imports");

	@POST
	@Path("/article/application/sn+xml")
	public Response doArticleXMLImport(@QueryParam("url")String url) throws UnsupportedEncodingException {
		url = URLDecoder.decode(url,"utf-8");
		if(url==null) {
			//TODO
		}
		try {
			final URL finaUrl = new URL(url);
			log.info("import directory {}", url);
			final UUID threadID = UUID.randomUUID();

			Runnable r = new Runnable() {
				@Override
				public void run() {
					try {

						snImporter.importData(finaUrl, "application/snxml+xml", null, null, currentUser);

					} catch (Exception ex) {
						log.error("exception during asynchronous method invocation", ex);
					}
				}
			};

			Thread t = new Thread(SN_IMPORTER_THREADS, r);
			t.setName("SNImporterService(Thread ID " + threadID + ")");
			t.start();
			return Response.ok().entity("{'tname':'" + t.getName() + "'}").build();
		} catch (Exception e) {
			log.error(e.getMessage());
			return Response.serverError().entity(e.getMessage()).build();
		}
	}

	@DELETE
	public Response stopArticleXMLImport(@QueryParam("tname")String tname) throws UnsupportedEncodingException {
		tname = URLDecoder.decode(tname,"utf-8");
		Thread[] threads = new Thread[SN_IMPORTER_THREADS.activeCount()];
		SN_IMPORTER_THREADS.enumerate(threads);
		for(Thread t : threads) {
			if(t!=null&&t.getName().equals(tname)) {
				//TODO
				t.destroy();
				return Response.ok().build();
			}
		}
		return Response.ok().entity("thread does not exist or is already stopped").build();
	}

	@GET
	@Path("/isActive")
	@Produces("application/json")
	public boolean isActiveArticleXMLImport(@QueryParam("tname")String tname) throws UnsupportedEncodingException {
		tname = URLDecoder.decode(tname,"utf-8");
		Thread[] threads = new Thread[SN_IMPORTER_THREADS.activeCount()];
		SN_IMPORTER_THREADS.enumerate(threads);
		for(Thread t : threads) {
			if(t!=null&&t.getName().equals(tname)&&t.isAlive()) return true;
		}
		return false;
	}

}
